/**   
 * @Title: MediaController.java 
 * @Package android.framework.media 
 * @Description: TODO
 * @author jtf@163.com   
 * @date 2013-7-19 上午11:35:41 
 * @version V1.0   
 */
package android.framework.media;

import java.util.Formatter;
import java.util.Locale;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.framework.media.bean.ProgramList;
import android.framework.util.L;
import android.framework.util.UIs;
import android.graphics.PixelFormat;
import android.media.AudioManager;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import android.framework.R;

/**
 * @ClassName: MediaController
 * @Description: TODO
 * @author jtf19@163.com
 * @date 2013-7-19 上午11:35:41
 * 
 */
@SuppressLint("NewApi")
public class MediaController extends FrameLayout implements BaseMediaController {

	private final String TAG = "MediaController";
	private boolean isOcto;
	private MediaPlayerControl mPlayer;
	private PlayController mPlayController;
	private OnSeekBarChangeListener mOnSeekBarChangeListener;
	private Context mContext;
	private View mAnchor;
	private View mRoot;
	private WindowManager mWindowManager;
	private Window mWindow;
	private View mDecor;
	private WindowManager.LayoutParams mDecorLayoutParams;
	private ProgressBar mProgress;
	private TextView mTime;// mEndTime, mCurrentTime,
	private boolean mShowing;
	private boolean mDragging;
	private static final int sDefaultTimeout = 3000;
	private static final int FADE_OUT = 1;
	private static final int SHOW_PROGRESS = 2;
	private boolean mUseFastForward;
	private boolean mFromXml;
	private boolean mListenersSet;
	private View.OnClickListener mNextListener, mPrevListener;
	StringBuilder mFormatBuilder;
	Formatter mFormatter;
	private ImageView mPauseButton;
	private ImageView mFfwdButton;
	private ImageView mRewButton;
	private ImageView mNextButton;
	private ImageView mPrevButton;
	private Button playBackButton;
	private AudioManager mAudioManager;
	private static int ffTime = 5000;// 快进快退时间

	private Bundle mBundle;
	private SeekBar mSoundSeek;
	private ImageView mSoundIcon;
	private int mSoundVolume;
	private TextView play_controller_time;
	private ImageView play_controller_net;
	private ImageView play_controller_battery;
	private TextView play_title;

	private boolean isRegStateReceiver = false;

	public void setOnSeekBarChangeListener(
			OnSeekBarChangeListener mOnSeekBarChangeListener) {
		this.mOnSeekBarChangeListener = mOnSeekBarChangeListener;
	}

	public MediaController(Context context) {
		// TODO Auto-generated constructor stub
		super(context);
		mRoot = this;
		mContext = context;
		mUseFastForward = true;
		mFromXml = true;
		mAudioManager = ((AudioManager) context
				.getSystemService(Context.AUDIO_SERVICE));
		initFloatingWindowLayout();
		initFloatingWindow();
	}

	public MediaController(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		mRoot = this;
		mContext = context;
		mUseFastForward = true;
		mFromXml = true;
		mRoot = this;
		mAudioManager = ((AudioManager) context
				.getSystemService(Context.AUDIO_SERVICE));
		initFloatingWindowLayout();
		initFloatingWindow();
	}

	public MediaController(Context context, boolean useFastForward) {
		super(context);
		mRoot = this;
		mContext = context;
		mUseFastForward = useFastForward;
		mAudioManager = ((AudioManager) context
				.getSystemService(Context.AUDIO_SERVICE));
		initFloatingWindowLayout();
		initFloatingWindow();
	}

	@Override
	public void onFinishInflate() {
		if (mRoot != null)
			initControllerView(mRoot);
	}

	private void initFloatingWindow() {
		mWindowManager = (WindowManager) mContext
				.getSystemService(Context.WINDOW_SERVICE);
		mWindow = makeNewWindow(mContext);
		mWindow.setWindowManager(mWindowManager, null, null);
		mWindow.requestFeature(Window.FEATURE_NO_TITLE);

		mDecor = mWindow.getDecorView();
		mDecor.setOnTouchListener(mTouchListener);
		mWindow.setContentView(this);
		mWindow.setBackgroundDrawableResource(android.R.color.transparent);

		// While the media controller is up, the volume control keys should
		// affect the media stream type
		mWindow.setVolumeControlStream(AudioManager.STREAM_MUSIC);

		setFocusable(true);
		setFocusableInTouchMode(true);
		setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
		requestFocus();
	}

	private Window makeNewWindow(Context context) {
		try {
			Window window = (Window) Class
					.forName("com.android.internal.policy.PolicyManager")
					.getMethod("makeNewWindow", new Class[] { Context.class })
					.invoke(null, new Object[] { context });
			// Window window = ((Activity)context).getWindow();
			return window;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	// Allocate and initialize the static parts of mDecorLayoutParams. Must
	// also call updateFloatingWindowLayout() to fill in the dynamic parts
	// (y and width) before mDecorLayoutParams can be used.
	private void initFloatingWindowLayout() {
		mDecorLayoutParams = new WindowManager.LayoutParams();
		WindowManager.LayoutParams p = mDecorLayoutParams;
		p.gravity = Gravity.TOP;
		p.height = LayoutParams.WRAP_CONTENT;
		p.x = 0;
		p.format = PixelFormat.TRANSLUCENT;
		p.type = WindowManager.LayoutParams.TYPE_APPLICATION_PANEL;
		p.flags |= WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM
				| WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
				| WindowManager.LayoutParams.FLAG_SPLIT_TOUCH;// |
																// WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
		// p.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
		// WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;
		p.token = null;
		p.windowAnimations = 0; // android.R.style.DropDownAnimationDown;
	}

	// Update the dynamic parts of mDecorLayoutParams
	// Must be called with mAnchor != NULL.
	private void updateFloatingWindowLayout() {
		int[] anchorPos = new int[2];
		mAnchor.getLocationOnScreen(anchorPos);

		WindowManager.LayoutParams p = mDecorLayoutParams;
		p.width = mAnchor.getWidth();
		p.y = anchorPos[1] + mAnchor.getHeight();
	}

	// This is called whenever mAnchor's layout bound changes
	private OnLayoutChangeListener mLayoutChangeListener = new OnLayoutChangeListener() {
		public void onLayoutChange(View v, int left, int top, int right,
				int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
			updateFloatingWindowLayout();
			if (mShowing) {
				mWindowManager.updateViewLayout(mDecor, mDecorLayoutParams);
			}
		}
	};

	private OnTouchListener mTouchListener = new OnTouchListener() {
		public boolean onTouch(View v, MotionEvent event) {
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				if (mShowing) {
					hide();
				}
			}
			// onTouchEvent(event);
			return false;
		}
	};

	/**
	 * Create the view that holds the widgets that control playback. Derived
	 * classes can override this to create their own.
	 * 
	 * @return The controller view.
	 * @hide This doesn't work as advertised
	 */
	protected View makeControllerView() {
		LayoutInflater inflate = (LayoutInflater) mContext
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mRoot = inflate.inflate(R.layout.play_controller, null);

		initControllerView(mRoot);

		return mRoot;
	}

	private void initControllerView(View v) {
		play_title = (TextView) v.findViewById(R.id.play_title);
		if(play_title != null){
			if(mBundle != null)
				play_title.setText(mBundle.getString("title",""));
		}
		
		play_controller_battery = (ImageView) v
				.findViewById(R.id.play_controller_battery);
		play_controller_time = (TextView) v
				.findViewById(R.id.play_controller_time);
		play_controller_net = (ImageView) v
				.findViewById(R.id.play_controller_net);

		playBackButton = (Button) v.findViewById(R.id.play_back);
		if (playBackButton != null) {
			playBackButton.setOnClickListener(mPlayBackListener);
		}

		mPauseButton = (ImageView) v.findViewById(R.id.play_pause);
		if (mPauseButton != null) {
			// mPauseButton.requestFocus();
			mPauseButton.setOnClickListener(mPauseListener);
		}

		mFfwdButton = (ImageView) v.findViewById(R.id.play_ffwd);
		if (mFfwdButton != null) {
			mFfwdButton.setOnClickListener(mFfwdListener);
			if (!mFromXml) {
				mFfwdButton.setVisibility(mUseFastForward ? View.VISIBLE
						: View.GONE);
			}
		}

		mRewButton = (ImageView) v.findViewById(R.id.play_rew);
		if (mRewButton != null) {
			mRewButton.setOnClickListener(mRewListener);
			if (!mFromXml) {
				mRewButton.setVisibility(mUseFastForward ? View.VISIBLE
						: View.GONE);
			}
		}

		// By default these are hidden. They will be enabled when
		// setPrevNextListeners() is called
		mNextButton = (ImageView) v.findViewById(R.id.play_next);
		if (mNextButton != null && !mFromXml && !mListenersSet) {
			mNextButton.setVisibility(View.GONE);
		}
		mPrevButton = (ImageView) v.findViewById(R.id.play_prev);
		if (mPrevButton != null && !mFromXml && !mListenersSet) {
			mPrevButton.setVisibility(View.GONE);
		}

		mProgress = (ProgressBar) v.findViewById(R.id.play_seekbar);
		if (mProgress != null) {
			if (mProgress instanceof SeekBar) {
				SeekBar seeker = (SeekBar) mProgress;
				seeker.setOnSeekBarChangeListener(mSeekListener);
			}
			mProgress.setMax(1000);
		}
		
		mTime = (TextView) v.findViewById(R.id.play_time);
		mFormatBuilder = new StringBuilder();
		mFormatter = new Formatter(mFormatBuilder, Locale.getDefault());

		mSoundSeek = (SeekBar) v.findViewById(R.id.sound_seekbar);
		if (mSoundSeek != null) {
			if (mSoundSeek instanceof SeekBar) {
				mSoundSeek.setMax(mAudioManager
						.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
				mSoundSeek.setOnSeekBarChangeListener(mSoundSeekListener);
			}
			adjustVolumeSeekBar();
		}

		mSoundIcon = (ImageView) v.findViewById(R.id.play_sound_icon);
		if (mSoundIcon != null) {
			mSoundIcon.setEnabled(true);
			mSoundIcon.setOnClickListener(mMuteListener);
			adjustSoundDrawable();
		}

		installPrevNextListeners();
	}

	private View.OnClickListener mMuteListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			int volume = mAudioManager
					.getStreamVolume(AudioManager.STREAM_MUSIC);
			if (volume > 0) {
				mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
			} else {
				mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
						mSoundVolume, 0);
			}
		}
	};

	private SeekBar.OnSeekBarChangeListener mSoundSeekListener = new SeekBar.OnSeekBarChangeListener() {

		@Override
		public void onStopTrackingTouch(SeekBar seekBar) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onStartTrackingTouch(SeekBar seekBar) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onProgressChanged(SeekBar seekBar, int progress,
				boolean fromUser) {
			// TODO Auto-generated method stub
			if (fromUser) {
				mAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
				mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
						progress, 0);
				adjustSoundDrawable();
			}
		}
	};

	/**
	 * Disable pause or seek buttons if the stream cannot be paused or seeked.
	 * This requires the control interface to be a MediaPlayerControlExt
	 */
	private void disableUnsupportedButtons() {
		try {
			if (mPauseButton != null && !mPlayer.canPause()) {
				mPauseButton.setEnabled(false);

			}
			if (mRewButton != null && !mPlayer.canSeekBackward()) {
				mRewButton.setEnabled(false);

			}
			if (mFfwdButton != null && !mPlayer.canSeekForward()) {
				mFfwdButton.setEnabled(false);

			}

		} catch (IncompatibleClassChangeError ex) {
			// We were given an old version of the interface, that doesn't have
			// the canPause/canSeekXYZ methods. This is OK, it just means we
			// assume the media can be paused and seeked, and so we don't
			// disable
			// the buttons.
		}
	}

	/**
	 * Show the controller on screen. It will go away automatically after
	 * 'timeout' milliseconds of inactivity.
	 * 
	 * @param timeout
	 *            The timeout in milliseconds. Use 0 to show the controller
	 *            until hide() is called.
	 */
	public void show(int timeout) {
		if (!mShowing && mAnchor != null) {
			setProgress();
			// if (mPauseButton != null) {
			// mPauseButton.requestFocus();
			// }
			disableUnsupportedButtons();
			updateFloatingWindowLayout();
			mWindowManager.addView(mDecor, mDecorLayoutParams);
			// L.i("show  === " + mShowing);
			mShowing = true;
		}
		updatePausePlay();

		// cause the progress bar to be updated even if mShowing
		// was already true. This happens, for example, if we're
		// paused with the progress bar showing the user hits play.
		mHandler.sendEmptyMessage(SHOW_PROGRESS);

		Message msg = mHandler.obtainMessage(FADE_OUT);
		if (timeout != 0) {
			mHandler.removeMessages(FADE_OUT);
			mHandler.sendMessageDelayed(msg, timeout);
		}
	}

	/**
	 * Show the controller on screen. It will go away automatically after 3
	 * seconds of inactivity.
	 */
	public void show() {
		show(sDefaultTimeout);
	}

	public boolean isShowing() {
		return mShowing;
	}

	/**
	 * Remove the controller from the screen.
	 */
	public void hide() {
		if (mAnchor == null)
			return;
		if (mShowing) {
			// L.i(TAG, "hide === " + mShowing);
			try {
				mHandler.removeMessages(SHOW_PROGRESS);
				mWindowManager.removeView(mDecor);
			} catch (IllegalArgumentException ex) {
				L.w(TAG, "already removed");
			}
			mShowing = false;
		}
	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case FADE_OUT:
				hide();
				break;
			case SHOW_PROGRESS:
				int pos = setProgress();
				if (!mDragging && mShowing && mPlayer.isPlaying()) {
					msg = obtainMessage(SHOW_PROGRESS);
					sendMessageDelayed(msg, 1000 - (pos % 1000));
				}
				break;
			}
		}
	};

	private String stringForTime(int timeMs) {
		int totalSeconds = timeMs / 1000;

		int seconds = totalSeconds % 60;
		int minutes = (totalSeconds / 60) % 60;
		int hours = totalSeconds / 3600;

		mFormatBuilder.setLength(0);
		if (hours > 0) {
			return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds)
					.toString();
		} else {
			return mFormatter.format("%02d:%02d", minutes, seconds).toString();
		}
	}

	private int setProgress() {
		// L.i("setProgress");
		if (mPlayer == null || mDragging) {
			return 0;
		}
		int position = mPlayer.getCurrentPosition();
		int duration = mPlayer.getDuration();
		if (mProgress != null) {
			if (duration > 0) {
				// use long to avoid overflow
				long pos = 1000L * position / duration;
				mProgress.setProgress((int) pos);
			}
			int percent = mPlayer.getBufferPercentage();
			mProgress.setSecondaryProgress(percent * 10);
		}

		if (mTime != null)
			mTime.setText(stringForTime(position) + "/"
					+ stringForTime(duration));

		return position;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			if (mShowing) {
				hide();
			} else {
				show();
			}
		}
		return true;
	}

	@Override
	public boolean onTrackballEvent(MotionEvent ev) {
		show(sDefaultTimeout);
		return false;
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		int keyCode = event.getKeyCode();
		final boolean uniqueDown = event.getRepeatCount() == 0
				&& event.getAction() == KeyEvent.ACTION_DOWN;
		if (keyCode == KeyEvent.KEYCODE_HEADSETHOOK
				|| keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE
				|| keyCode == KeyEvent.KEYCODE_SPACE) {
			if (uniqueDown) {
				doPauseResume();
				show(sDefaultTimeout);
				if (mPauseButton != null) {
					mPauseButton.requestFocus();
				}
			}
			return true;
		} else if (keyCode == KeyEvent.KEYCODE_MEDIA_PLAY) {
			if (uniqueDown && !mPlayer.isPlaying()) {
				mPlayer.start();
				updatePausePlay();
				show(sDefaultTimeout);
			}
			return true;
		} else if (keyCode == KeyEvent.KEYCODE_MEDIA_STOP
				|| keyCode == KeyEvent.KEYCODE_MEDIA_PAUSE) {
			if (uniqueDown && mPlayer.isPlaying()) {
				mPlayer.pause();
				updatePausePlay();
				show(sDefaultTimeout);
			}
			return true;
		} else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN
				|| keyCode == KeyEvent.KEYCODE_VOLUME_UP
				|| keyCode == KeyEvent.KEYCODE_VOLUME_MUTE
				|| keyCode == KeyEvent.KEYCODE_CAMERA) {
			// don't show the controls for volume adjustment
			return super.dispatchKeyEvent(event);
		} else if (keyCode == KeyEvent.KEYCODE_BACK
				|| keyCode == KeyEvent.KEYCODE_MENU) {
			if (uniqueDown) {
				hide();
			}
			return true;
		}

		show(sDefaultTimeout);
		return super.dispatchKeyEvent(event);
	}

	private View.OnClickListener mPlayBackListener = new View.OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			if (mPlayController != null) {// doback
				L.i("doback");
				mPlayController.onFinish();
			}
//			if (mContext instanceof PlayActivity) {
//				Log.i("Mediaplayer", "activity finish &&& ");
//				((PlayActivity) mContext).finish();
//			}
		}
	};

	private View.OnClickListener mPauseListener = new View.OnClickListener() {
		public void onClick(View v) {
			doPauseResume();
			show(sDefaultTimeout);
		}
	};

	private void updatePausePlay() {
		if (mRoot == null || mPauseButton == null)
			return;
		if (mPlayer.isPlaying()) {
			mPauseButton.setImageResource(R.drawable.play_controller_pause_btn);
		} else {
			mPauseButton.setImageResource(R.drawable.play_controller_play_btn);
		}
	}

	private void doPauseResume() {
		if (mPlayer.isPlaying()) {
			mPlayer.pause();
		} else {
			mPlayer.start();
		}
		updatePausePlay();
	}

	// There are two scenarios that can trigger the seekbar listener to trigger:
	//
	// The first is the user using the touchpad to adjust the posititon of the
	// seekbar's thumb. In this case onStartTrackingTouch is called followed by
	// a number of onProgressChanged notifications, concluded by
	// onStopTrackingTouch.
	// We're setting the field "mDragging" to true for the duration of the
	// dragging
	// session to avoid jumps in the position in case of ongoing playback.
	//
	// The second scenario involves the user operating the scroll ball, in this
	// case there WON'T BE onStartTrackingTouch/onStopTrackingTouch
	// notifications,
	// we will simply apply the updated position without suspending regular
	// updates.
	private OnSeekBarChangeListener mSeekListener = new OnSeekBarChangeListener() {
		public void onStartTrackingTouch(SeekBar bar) {
			L.i("onStartTrackingTouch");
			if (mOnSeekBarChangeListener != null)
				mOnSeekBarChangeListener.onStartTrackingTouch(bar);
			show(3600000);

			mDragging = true;

			// By removing these pending progress messages we make sure
			// that a) we won't update the progress while the user adjusts
			// the seekbar and b) once the user is done dragging the thumb
			// we will post one of these messages to the queue again and
			// this ensures that there will be exactly one message queued up.
			mHandler.removeMessages(SHOW_PROGRESS);
		}

		public void onProgressChanged(SeekBar bar, int progress,
				boolean fromuser) {
			if (!fromuser) {
				// We're not interested in programmatically generated changes to
				// the progress bar's position.
				return;
			}
			L.i("from user" + progress);
			long duration = mPlayer.getDuration();
			long newposition = (duration * progress) / 1000L;
			L.i("======    " + newposition);
			mPlayer.seekTo((int) newposition);
			if (mTime != null)
				mTime.setText(stringForTime((int) newposition) + "/"
						+ stringForTime((int) duration));
		}

		public void onStopTrackingTouch(SeekBar bar) {
			mDragging = false;
			setProgress();
			updatePausePlay();
			show(sDefaultTimeout);
			mHandler.sendEmptyMessage(SHOW_PROGRESS);

		}
	};

	private View.OnClickListener mRewListener = new View.OnClickListener() {
		public void onClick(View v) {
			int pos = mPlayer.getCurrentPosition();
			pos -= ffTime; // milliseconds
			mPlayer.seekTo(pos);
			setProgress();
			show(sDefaultTimeout);
		}
	};

	private View.OnClickListener mFfwdListener = new View.OnClickListener() {
		public void onClick(View v) {
			int pos = mPlayer.getCurrentPosition();
			pos += ffTime; // milliseconds
			mPlayer.seekTo(pos);
			setProgress();
			show(sDefaultTimeout);
		}
	};

	private void installPrevNextListeners() {
		if (mNextButton != null) {
			mNextButton.setOnClickListener(mNextListener);
			mNextButton.setEnabled(mNextListener != null);
		}

		if (mPrevButton != null) {
			mPrevButton.setOnClickListener(mPrevListener);
			mPrevButton.setEnabled(mPrevListener != null);
		}
	}

	public void setPrevNextListeners(View.OnClickListener next,
			View.OnClickListener prev) {
		mNextListener = next;
		mPrevListener = prev;
		mListenersSet = true;

		if (mRoot != null) {
			installPrevNextListeners();

			if (mNextButton != null && !mFromXml) {
				mNextButton.setVisibility(View.VISIBLE);
			}
			if (mPrevButton != null && !mFromXml) {
				mPrevButton.setVisibility(View.VISIBLE);
			}
		}
	}

	@Override
	protected void onWindowVisibilityChanged(int visibility) {
		// TODO Auto-generated method stub
		super.onWindowVisibilityChanged(visibility);
		if (visibility == View.VISIBLE) {
			registerReceiver();
			UIs.changeTimeState(this.play_controller_time);
		} else {
			unregisterReceiver();
		}
	}

	// //////===================== impls
	// ========================//////////////////

	@Override
	public void setEnabled(boolean enabled) {
		if (mPauseButton != null) {
			mPauseButton.setEnabled(enabled);
			L.i("mPauseButton  " + mPauseButton.isEnabled());
		}
		if (mFfwdButton != null) {
			mFfwdButton.setEnabled(enabled);
			L.i("   mFfwdButton   " + mFfwdButton.isEnabled());
		}
		if (mRewButton != null) {
			mRewButton.setEnabled(enabled);
			L.i("   mRewButton   " + mRewButton.isEnabled());
		}
		if (mNextButton != null) {
			mNextButton.setEnabled(enabled && mNextListener != null);
		}
		if (mPrevButton != null) {
			mPrevButton.setEnabled(enabled && mPrevListener != null);
		}
		if (mProgress != null) {
			mProgress.setEnabled(enabled);
		}
		disableUnsupportedButtons();
		super.setEnabled(enabled);
	}

	public void setMediaPlayer(MediaPlayerControl player) {
		mPlayer = player;
		updatePausePlay();
	}

	/**
	 * Set the view that acts as the anchor for the control view. This can for
	 * example be a VideoView, or your Activity's main view.
	 * 
	 * @param view
	 *            The view to which to anchor the controller when it is visible.
	 */
	public void setAnchorView(View view) {
		if (mAnchor != null) {
			mAnchor.removeOnLayoutChangeListener(mLayoutChangeListener);
		}
		mAnchor = view;
		if (mAnchor != null) {
			// mAnchor.addOnLayoutChangeListener(mLayoutChangeListener);
		}

		FrameLayout.LayoutParams frameParams = new FrameLayout.LayoutParams(
				ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.MATCH_PARENT);

		removeAllViews();
		View v = makeControllerView();
		addView(v, frameParams);
	}

	@Override
	public void adjustSoundDrawable() {
		// TODO Auto-generated method stub
		int volume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
		if (volume == 0) {
			mSoundIcon.setImageResource(R.drawable.sound_zero);
		} else {
			if (volume > 0 && volume <= 5) {
				mSoundIcon.setImageResource(R.drawable.sound_one);
			} else if (volume > 3 && volume <= 10) {
				mSoundIcon.setImageResource(R.drawable.sound_two);
			} else if (volume > 10) {
				mSoundIcon.setImageResource(R.drawable.sound_three);
			}
			mSoundVolume = volume;
		}

	}
	
	public void volumeDown(){
		int volume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
		volume --;
		if(volume<0)
			volume = 0;
		mAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
		mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
				volume, -2);
	}
	
	public void volumeUp(){
		int volume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
		volume ++;
		if(volume>mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC))
			volume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		mAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
		mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
				volume, -2);
	}
	
	@Override
	public void adjustVolumeSeekBar() {
		// TODO Auto-generated method stub
		int volume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
		mSoundSeek.setProgress(volume);
	}

	@Override
	public void onActivityResult(int paramInt1, int paramInt2,
			Intent paramIntent) {
		// TODO Auto-generated method stub

	}

	@Override
	public void setAlbum(Album paramAlbum) {
		// TODO Auto-generated method stub

	}

	@Override
	public void setHasHigh(boolean paramBoolean) {
		// TODO Auto-generated method stub

	}

	@Override
	public void setHasLow(boolean paramBoolean) {
		// TODO Auto-generated method stub

	}

	@Override
	public void setHd(boolean paramBoolean) {
		// TODO Auto-generated method stub

	}

	@Override
	public void setLive(boolean paramBoolean) {
		// TODO Auto-generated method stub

	}

	@Override
	public void setProgramList(ProgramList programList) {
		// TODO Auto-generated method stub

	}

	@Override
	public void setMbundle(Bundle bundle) {
		// TODO Auto-generated method stub
		this.mBundle = bundle;

	}

	@Override
	public void setOnlyLive(boolean paramBoolean) {
		// TODO Auto-generated method stub

	}

	@Override
	public void setPlayController(PlayController playController) {
		// TODO Auto-generated method stub
		this.mPlayController = playController;

	}

	@Override
	public void setWebPlay(boolean paramBoolean) {
		// TODO Auto-generated method stub

	}

	@Override
	public void showFull() {
		// TODO Auto-generated method stub

	}

	@Override
	public void unregisterReceiver() {
		// TODO Auto-generated method stub
		if ((!this.isRegStateReceiver) || (this.mContext == null))
			return;
		this.mContext.unregisterReceiver(mBroadcastReceiver);
		this.isRegStateReceiver = false;

	}

	public void registerReceiver() {
		if (this.isRegStateReceiver)
			return;
		IntentFilter localIntentFilter = new IntentFilter();
		localIntentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
		localIntentFilter.addAction("android.intent.action.TIME_TICK");
		localIntentFilter.addAction("android.intent.action.BATTERY_CHANGED");
		if (this.mContext == null)
			return;
		this.mContext.registerReceiver(this.mBroadcastReceiver,
				localIntentFilter);
		this.isRegStateReceiver = true;
	}

	private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
		public void onReceive(Context paramContext, Intent paramIntent) {
			if ("android.intent.action.TIME_TICK".equals(paramIntent
					.getAction())) {
				if (MediaController.this.play_controller_time != null)
					UIs.changeTimeState(MediaController.this.play_controller_time);
			} else if ("android.net.conn.CONNECTIVITY_CHANGE"
					.equals(paramIntent.getAction())) {
				if (MediaController.this.play_controller_net != null)
					UIs.changeNetState(MediaController.this.getContext(),
							MediaController.this.play_controller_net);
			} else if ("android.intent.action.BATTERY_CHANGED"
					.equals(paramIntent.getAction())) {
				int i = paramIntent.getIntExtra("status",
						BatteryManager.BATTERY_STATUS_UNKNOWN);
				int j = paramIntent.getExtras().getInt("level", 0);
				int k = paramIntent.getExtras().getInt("scale", 100);
				int l = j * 100 / k;
				if (MediaController.this.play_controller_battery != null)
					UIs.changeBatteryState(i, l,
							MediaController.this.play_controller_battery);
			}
		}
	};

	@Override
	public void updateLiveChannelProgram() {
		// TODO Auto-generated method stub

	}

	@Override
	public void updateSkipState() {
		// TODO Auto-generated method stub

	}

	@Override
	public void setOcto(boolean isOcto) {
		// TODO Auto-generated method stub
		this.isOcto = isOcto;
	}

	public boolean getIsOcto() {
		return isOcto;
	}

}
